//
//  RHMQReportParamController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/8/14.
//

#import "RHMQReportParamController.h"
#import "RHMQSelPointTypeController.h"
#import "RHMQEndPointModel.h"
#import "RHMQParamModel.h"
#import "RHMQTTManage.h"
#import "RHMQDevModel.h"

@interface RHMQReportParamController ()<UITableViewDelegate ,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,copy) NSArray *dataArray;

@property (nonatomic ,strong) QMUILabel *titleLab;

@property (nonatomic ,strong) QMUILabel *codeLab;

@property (nonatomic ,strong) RHMQEndPointModel *endPointModel;

@property (nonatomic ,strong) RHMQEndPointModel *curEndPointModel;


@end

@implementation RHMQReportParamController


- (NSArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSArray array];
    }
    return _dataArray;
}

- (void)setCurEndPointModel:(RHMQEndPointModel *)curEndPointModel{
    _curEndPointModel = curEndPointModel;
    [self getDataList];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self.navigationItem setTitle:@"参数上报"];
    [self.view setBackgroundColor:CFTabViewBgColor];
    [self setupUI];
}


- (void)setupUI{
    
    QMUIButton *submitBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [submitBtn setFrame:CGRectMake(0, 0,40, 64)];
    [submitBtn setBackgroundColor:UIColor.clearColor];
    [submitBtn setTitleColor:CFMainColor forState:UIControlStateNormal];
    [submitBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [submitBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [submitBtn setTitle:@"上报" forState:UIControlStateNormal];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:submitBtn];
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
    UIView *view = [[UIView alloc] init];
    [view setBackgroundColor:UIColor.whiteColor];
    [self.view addSubview:view];
    
    _titleLab = [[QMUILabel alloc] init];
    [_titleLab setTextAlignment:NSTextAlignmentLeft];
    [_titleLab setFont:[UIFont systemFontOfSize:15]];
    [_titleLab setTextColor:kCOLOR_HEX(@"999999")];
    [_titleLab setText:@"请选择端点"];
    [view addSubview:_titleLab];
    
    _codeLab = [[QMUILabel alloc] init];
    [_codeLab setTextAlignment:NSTextAlignmentRight];
    [_codeLab setFont:[UIFont systemFontOfSize:15]];
    [_codeLab setTextColor:kCOLOR_HEX(@"666666")];
    [_codeLab setText:@""];
    [view addSubview:_codeLab];
    
    UIImageView *arrowV = [[UIImageView alloc] init];
    [arrowV setImage:[UIImage imageNamed:@"arrow"]];
    [view addSubview:arrowV];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [self.view addSubview:_tableView];
    
    UITapGestureRecognizer *tapView = [[UITapGestureRecognizer alloc] init];
    view.userInteractionEnabled = YES;
    [view addGestureRecognizer:tapView];
    
    
    kWeakSelf;
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(5);
        make.height.mas_equalTo(50);
    }];
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_offset(0);
        make.left.mas_offset(15);
        make.width.mas_equalTo(100);
    }];
    
    [_codeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.titleLab.mas_right);
        make.top.bottom.equalTo(weakSelf.titleLab);
        make.right.equalTo(arrowV.mas_left).offset(-5);
    }];
    
    [arrowV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.right.mas_offset(-15);
        make.centerY.mas_offset(0);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(60, 0, 0, 0));
    }];
    
    [tapView.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        [weakSelf selectEndPoint];
    }];
    
    [[submitBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf submitDataAction];
    }];
    
    
    QMUIButton *getDataBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [getDataBtn setFrame:CGRectMake(0, 0,40, 64)];
    [getDataBtn setBackgroundColor:CMainColorGreen];
    [getDataBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [getDataBtn.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [getDataBtn setTitle:@"获取端点参数数据" forState:UIControlStateNormal];
    [self.view addSubview:getDataBtn];
    [getDataBtn addTarget:self action:@selector(reportParamsData) forControlEvents:UIControlEventTouchUpInside];
    
    [getDataBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(30);
            make.right.bottom.mas_offset(-30);
            make.height.offset(45);
            
    }];
    getDataBtn.hidden = YES;
}

//选择端点
- (void)selectEndPoint{
    RHMQSelPointTypeController *vc = [[RHMQSelPointTypeController alloc] initWithModel:self.curEndPointModel];
    [self.navigationController pushViewController:vc animated:YES];
    kWeakSelf;
    vc.callBackBlock = ^(RHMQEndPointModel * _Nonnull model,NSString *deviceTypeCode) {
        [weakSelf.titleLab setText:model.type];
        [weakSelf.codeLab setText:model.sn];
        weakSelf.curEndPointModel = model;
    };
}

//上报参数
- (void)submitDataAction{
    [self reportParamsData];
}

#pragma mark - Network

//获取参数列表数据
- (void)getDataList{
    if(!_curEndPointModel){ 
        return;
    }
    NSDictionary *para = @{@"endpointTypeCode":_curEndPointModel.type,
                           @"deviceId":[RHMQTTManage shareMQTTManage].devModel.devId,
                           @"sn":_curEndPointModel.sn,
                           @"deviceTypeCode":[RHMQTTManage shareMQTTManage].devModel.deviceTypeCode
    };
    [QMUITips showLoadingInView:self.view];
    [RHMQParamModel startWithCompletionAPIKey:H_devParameterConfig argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                self.dataArray = resultModel.data;
                [self.tableView reloadData];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
    }];
    
}



#pragma mark ---------  上报参数数据  ------

- (void)reportParamsData{
    
    if(!_curEndPointModel){
        [QMUITips showWithText:@"请选择端点"];
        return;
    }
    NSMutableArray *array = [NSMutableArray array];
    
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHMQParamModel *model = obj;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [model.thresholdParamConfigVos enumerateObjectsUsingBlock:^(RHMQParamModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [dic setObject:ValidNullData(obj.currentValue) forKey:obj.paramName];
        }];
        [array addObject:@{model.thresholdCode:dic}];
    }];
    
    NSDictionary *dic = @{@"dataType":@0,
                          @"deviceId":[RHMQTTManage shareMQTTManage].devModel.devId,
                          @"password":[RHMQTTManage shareMQTTManage].devModel.secretKey,
                          @"endpointCode":_curEndPointModel.type,
                          @"id":@"1",
                          @"jsonData":[array yy_modelToJSONString],
                          @"sn":_curEndPointModel.sn};

    
    [QMUITips showLoading:@"report..." inView:self.view];
    [RHMQParamModel startWithCompletionAPIKey:D_devUploadParam argument:dic requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {

        if(resultModel.code == 200){
            [QMUITips showSucceed:@"successful"];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

#pragma mark - UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHMQParamModel *model = self.dataArray[section];
    return model.thresholdParamConfigVos.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UITableViewHeaderFooterView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NSString stringWithFormat:@"header_%ld",section]];
    
    RHMQParamModel *model = self.dataArray[section];
    
    if(headView == nil){
        headView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:[NSString stringWithFormat:@"header_%ld",section]];
        [headView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        
        [headView.contentView setBackgroundColor:UIColor.whiteColor];
        //UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
        [headView setBackgroundColor:[UIColor whiteColor]];
        
        UIView *markV = [[UIView alloc] init];
        [markV setBackgroundColor:CFMainColor];
        [headView addSubview:markV];
        
        QMUILabel *titleLab = [[QMUILabel alloc] init];
        [titleLab setTextAlignment:NSTextAlignmentLeft];
        [titleLab setFont:[UIFont boldSystemFontOfSize:15]];
        [titleLab setTextColor:kCOLOR_HEX(@"666666")];
        [headView addSubview:titleLab];
        
//        UIView *bgV = [[UIView alloc] init];
//        [bgV setBackgroundColor:UIColor.clearColor];
//        [bgV.layer setCornerRadius:5];
//        [bgV.layer setBorderWidth:1];
//        [bgV.layer setBorderColor:kCOLOR_HEX(@"eeeeee").CGColor];
//        [headView addSubview:bgV];
        
//        QMUITextField *textField = [[QMUITextField alloc] init];
//        [textField setKeyboardType:UIKeyboardTypeNumberPad];
//        [textField setPlaceholder:@"请输入"];
//        [bgV addSubview:textField];
        
        [markV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(5, 30));
            make.left.mas_offset(2);
            make.centerY.mas_offset(0);
        }];
        
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.bottom.mas_offset(0);
            make.width.mas_equalTo(200);
        }];
        
//        [bgV mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.height.mas_equalTo(40);
//            make.centerY.mas_offset(0);
//            make.right.mas_offset(-20);
//            make.width.mas_equalTo(100);
//        }];
        
//        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.edges.insets(UIEdgeInsetsMake(5, 5, 5, 5));
//        }];

//        [[RACSignal merge:@[textField.rac_textSignal, RACObserve(textField, text)]] subscribeNext:^(NSString* text){
//            model.content = text;
//        }];
        
        [titleLab setText:model.thresholdName];
    }
    
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RHMQParamModel *model = self.dataArray[indexPath.section];
    RHMQParamModel *item_model = model.thresholdParamConfigVos[indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"cell_%ld_%ld",indexPath.section,indexPath.row]];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"cell_%ld_%ld",indexPath.section,indexPath.row]];
        
        //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
        [cell.textLabel setTextColor:kCOLOR_HEX(@"666666")];
        
        UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        [bgV setBackgroundColor:UIColor.clearColor];
        [bgV.layer setCornerRadius:5];
        [bgV.layer setBorderWidth:1];
        [bgV.layer setBorderColor:kCOLOR_HEX(@"eeeeee").CGColor];
        
        QMUITextField *textField = [[QMUITextField alloc] init];
        [textField setKeyboardType:UIKeyboardTypeNumberPad];
        [textField setPlaceholder:@"请输入"];
        [bgV addSubview:textField];

        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(5, 5, 5, 5));
        }];
        
        [cell setAccessoryView:bgV];
        
        
        [[RACSignal merge:@[textField.rac_textSignal, RACObserve(textField, text)]] subscribeNext:^(NSString* text){
            NSLog(@"text ==== %@",text);
            item_model.currentValue = text;
        }];
        
    }

    [cell.textLabel setText:SafeStr(item_model.paramNickName)];
    
    
//    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//    [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
//    [cell.textLabel setTextColor:kCOLOR_HEX(@"666666")];
//
//    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
//    [bgV setBackgroundColor:UIColor.clearColor];
//    [bgV.layer setCornerRadius:5];
//    [bgV.layer setBorderWidth:1];
//    [bgV.layer setBorderColor:kCOLOR_HEX(@"eeeeee").CGColor];
//
//    QMUITextField *textField = [[QMUITextField alloc] init];
//    [textField setKeyboardType:UIKeyboardTypeNumberPad];
//    [textField setPlaceholder:@"请输入"];
//    [bgV addSubview:textField];
//
//    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.insets(UIEdgeInsetsMake(5, 5, 5, 5));
//    }];
//
//    [cell setAccessoryView:bgV];
//
//    RHMQParamModel *model = self.dataArray[indexPath.section];
//    RHMQParamModel *item_model = model.thresholdParamConfigVos[indexPath.row];
//    [cell.textLabel setText:SafeStr(item_model.paramNickName)];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
}


@end
